package com.uzai.console.service.md.mdexchange.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.User;
import com.uzai.common.enums.AccDetailTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.md.mdexchange.MdExchangeIdDto;
import com.uzai.console.dto.md.mdexchange.MdExchangeQuery;
import com.uzai.console.dto.md.mdexchange.MdExchangeUpdateExptimeDto;
import com.uzai.console.entity.MdActivity;
import com.uzai.console.entity.MdExchange;
import com.uzai.console.entity.MdGoods;
import com.uzai.console.entity.UserAccDetail;
import com.uzai.console.mapper.MdActivityMapper;
import com.uzai.console.mapper.MdExchangeMapper;
import com.uzai.console.mapper.MdGoodsMapper;
import com.uzai.console.mapper.UserAccDetailMapper;
import com.uzai.console.dto.md.mdgoods.ExemptionGoodsUpdateRedeemedQuantityDto;
import com.uzai.console.entity.*;
import com.uzai.console.mapper.*;
import com.uzai.console.service.feign.UzaiBusinessFeignService;
import com.uzai.console.service.md.mdexchange.MdExchangeService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.vo.md.mdexchange.MdExchangeVo;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 免单兑换记录
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class MdExchangeServiceImpl implements MdExchangeService {

    Logger logger = LoggerFactory.getLogger(MdExchangeServiceImpl.class);

    @Autowired
    private MdExchangeMapper mdExchangeMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private MdActivityMapper mdActivityMapper;
    @Autowired
    private MdGoodsMapper mdGoodsMapper;
    @Autowired
    private UserAccDetailMapper userAccDetailMapper;
    @Autowired
    private UzaiBusinessFeignService uzaiBusinessFeignService;

    /**
     * 查询免单兑换记录列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdExchangeQuery
     * @return null
     */
    public Page<MdExchangeVo> findMdExchangeList(MdExchangeQuery mdExchangeQuery){
        //新建返回到页面的LIST对象
        List<MdExchangeVo> mdExchangeVoList = new ArrayList<>();

        if(mdExchangeQuery.getActivityId() != null){
            MdActivity mdActivity = mdActivityMapper.selectByActivityId(mdExchangeQuery.getActivityId(), mdExchangeQuery.getMerId());
            if(mdActivity != null){
                mdExchangeQuery.setActivityId(mdActivity.getId());
            }
        }

        //执行分页查询对象
        Page<MdExchange> page = new Page<>();
        mdExchangeQuery.convert(page);
        ArrayList<MdExchange> mdExchangeList =  mdExchangeMapper.findByList(page, mdExchangeQuery);
        if(mdExchangeList != null && mdExchangeList.size() > 0){
            for (MdExchange mdExchange : mdExchangeList){
                MdExchangeVo mdExchangeVo = new MdExchangeVo();
                BeanUtils.copyProperties(mdExchange, mdExchangeVo);

                if(mdExchange.getUserId() != null){
                    User userInfo = userService.findUserInfo(mdExchange.getUserId(), null, mdExchange.getMerId());
                    if(userInfo != null){
                        mdExchangeVo.setUserName(userInfo.getNickName());
                    }
                }

                //查询活动id
                if(mdExchange.getActivityId() != null){
                    MdActivity mdActivity = mdActivityMapper.selectById(mdExchange.getActivityId(), mdExchange.getMerId());
                    if(mdActivity != null){
                        mdExchangeVo.setActivityId(mdActivity.getActivityId());
                    }
                }

                mdExchangeVoList.add(mdExchangeVo);
            }
        }
        //返回到页面分页对象
        Page<MdExchangeVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(mdExchangeVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询免单兑换记录详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdExchangeIdDto
     * @return null
     */
    public MdExchangeVo findMdExchange(MdExchangeIdDto mdExchangeIdDto){
        if(mdExchangeIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        MdExchange mdExchange = mdExchangeMapper.selectById(mdExchangeIdDto.getId(), mdExchangeIdDto.getMerId());

        if(mdExchange == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该免单兑换记录不存在");
        }

        MdExchangeVo mdExchangeVo = new MdExchangeVo();
        BeanUtils.copyProperties(mdExchange, mdExchangeVo);

        if(mdExchange.getUserId() != null){
            User userInfo = userService.findUserInfo(mdExchange.getUserId(), null, mdExchange.getMerId());
            if(userInfo != null){
                mdExchangeVo.setUserName(userInfo.getNickName());
            }
        }

        //查询活动id
        if(mdExchange.getActivityId() != null){
            MdActivity mdActivity = mdActivityMapper.selectById(mdExchange.getActivityId(), mdExchange.getMerId());
            if(mdActivity != null){
                mdExchangeVo.setActivityId(mdActivity.getActivityId());
            }
        }

        return mdExchangeVo;
    }

    @Override
    @Transactional
    public void deleMdExchange(MdExchangeIdDto mdExchangeIdDto) {

        int nowTime = DateUtil.getNowTime();

        if(mdExchangeIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        MdExchange mdExchange = mdExchangeMapper.selectById(mdExchangeIdDto.getId(), mdExchangeIdDto.getMerId());
        if(mdExchange == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该免单兑换记录不存在");
        }

        if(mdExchange.getChildOrderNo()!=null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该免单兑换记录已下单");
        }

        //删除兑换记录
        int deleResult = mdExchangeMapper.deleteById(mdExchange.getId(), mdExchange.getMerId());
        if(deleResult!=1){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "删除该免单兑换记录失败");
        }

        /**
         * 判断兑换记录是否无效，
         * 如果是无效，则直接删除兑换记录就行，因为处理兑换记录无效时已经处理了商品的兑换次数和会员的积分
         * 如果是有效商品，则还得处理商品的兑换次数和兑换会员积分
         */
        if(Tools.getInteger(mdExchange.getStatus()).intValue() == 1){//有效兑换兑换记录
            if(Tools.getInteger(mdExchange.getSource()).intValue() == 0){ //运营商私有商品
                //查询兑换商品
                MdGoods mdGoods = mdGoodsMapper.selectById(mdExchange.getGoodsId(), mdExchange.getMerId());
                if(mdGoods != null){ //如果商品存在，则需要找回商品的兑换次数
                    //修改兑换商品已经领取数量
                    mdGoods.setUsedCount(mdGoods.getUsedCount()-1);
                    mdGoods.setUpdateTime(nowTime);
                    int i = mdGoodsMapper.updateById(mdGoods);
                    if(i!=1){
                        throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改兑换商品已经领取数量失败");
                    }

                    //获取兑换积分
                    Integer redeemPoints = mdGoods.getRedeemPoints();
                    //修改用户积分
                    User userInfo = userService.findUserInfo(mdExchange.getUserId(), null, mdExchange.getMerId());
                    if(userInfo != null){
                        userInfo.setIntegral(userInfo.getIntegral()+redeemPoints);
                        userInfo.setUpdateTime(nowTime);
                        int j = userService.updateBalance(userInfo);
                        if(j!=1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改用户积分失败");
                        }

                        //增加账号入账明细
                        UserAccDetail wechatUserAccDetail = new UserAccDetail();
                        wechatUserAccDetail.setId(IdWorker.getId());
                        wechatUserAccDetail.setMerId(userInfo.getMerId());
                        wechatUserAccDetail.setUserId(userInfo.getId());
                        wechatUserAccDetail.setDeviceUniqueId(userInfo.getDeviceUniqueId());
                        wechatUserAccDetail.setDeviceType(userInfo.getDeviceType());
                        wechatUserAccDetail.setChangeInte(redeemPoints);
                        wechatUserAccDetail.setNewInte(userInfo.getIntegral());
                        wechatUserAccDetail.setChangeBal(0D);
                        wechatUserAccDetail.setNewBal(userInfo.getBalance());
                        wechatUserAccDetail.setType(AccDetailTypeEnum.CHANGE_OPERATOR.getValue());
                        wechatUserAccDetail.setRemark("删除兑换记录");
                        wechatUserAccDetail.setCreateTime(nowTime);
                        wechatUserAccDetail.setUpdateTime(nowTime);
                        int insert = userAccDetailMapper.insert(wechatUserAccDetail);
                        if(insert!=1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号入账明细失败");
                        }
                    }
                }
            }else{//官方商品
                ExemptionGoodsUpdateRedeemedQuantityDto exemptionGoodsUpdateRedeemedQuantityDto = new ExemptionGoodsUpdateRedeemedQuantityDto();
                exemptionGoodsUpdateRedeemedQuantityDto.setId(mdExchange.getGoodsId());
                exemptionGoodsUpdateRedeemedQuantityDto.setPlatformType(mdExchange.getPlatform());
                exemptionGoodsUpdateRedeemedQuantityDto.setRedeemedQuantity(-1); //回收兑换次数
                UzaiRespVo<Object> uzaiRespVo = uzaiBusinessFeignService.updateExemptionGoodsRedeemedQuantity(exemptionGoodsUpdateRedeemedQuantityDto);
                logger.info("删除免单官方兑换记录，减少官方商品已兑换次数，para={}，result={}", JSONObject.toJSONString(exemptionGoodsUpdateRedeemedQuantityDto), JSONObject.toJSONString(uzaiRespVo));
            }
        }

    }


    /**
     * 免单兑换记录修改有效期
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdExchangeUpdateExptimeDto
     * @return null
     */
    public void updateExptime(MdExchangeUpdateExptimeDto mdExchangeUpdateExptimeDto){
        int nowTime = DateUtil.getNowTime();

        if(mdExchangeUpdateExptimeDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        if(mdExchangeUpdateExptimeDto.getExptime() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入有效期");
        }

        if(mdExchangeUpdateExptimeDto.getExptime() <= nowTime){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "有效期不能小于现在时间");
        }

        MdExchange mdExchange = mdExchangeMapper.selectById(mdExchangeUpdateExptimeDto.getId(), mdExchangeUpdateExptimeDto.getMerId());
        if(mdExchange == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该免单兑换记录不存在");
        }

        mdExchange.setExptime(mdExchangeUpdateExptimeDto.getExptime());
        mdExchange.setStatus(1); //有效
        mdExchange.setUpdateTime(nowTime);
        mdExchangeMapper.updateStatusById(mdExchange);
    }

    /**
     * 自动检测免单兑换记录是否过期
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdExchange
     * @return null
     */
    @Override
    public void autoCheckMdExchangeExpired(MdExchange mdExchange){
        int nowTime = DateUtil.getNowTime();

        if(Tools.getInteger(mdExchange.getStatus()).intValue() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该免单兑换已经过期无效");
        }

        if(Tools.getInteger(mdExchange.getExptime()).intValue() == 0 || mdExchange.getExptime() > nowTime){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该免单商品兑换记录还未过期");
        }

        //修改免单商品已经过期
        mdExchange.setStatus(0); //无效
        mdExchange.setUpdateTime(nowTime);
        mdExchangeMapper.updateStatusById(mdExchange);

        //私有免单商品
        if(Tools.getInteger(mdExchange.getSource()).intValue() == 0){
            //查询兑换商品
            MdGoods mdGoods = mdGoodsMapper.selectById(mdExchange.getGoodsId(), mdExchange.getMerId());
            if(mdGoods != null){
                //修改兑换商品已经领取数量
                mdGoods.setUsedCount(mdGoods.getUsedCount()-1);
                mdGoods.setUpdateTime(nowTime);
                mdGoodsMapper.updateById(mdGoods);
            }
        }else{ //官方免单商品
            ExemptionGoodsUpdateRedeemedQuantityDto exemptionGoodsUpdateRedeemedQuantityDto = new ExemptionGoodsUpdateRedeemedQuantityDto();
            exemptionGoodsUpdateRedeemedQuantityDto.setId(mdExchange.getGoodsId());
            exemptionGoodsUpdateRedeemedQuantityDto.setPlatformType(mdExchange.getPlatform());
            exemptionGoodsUpdateRedeemedQuantityDto.setRedeemedQuantity(-1); //回收兑换次数
            UzaiRespVo<Object> uzaiRespVo = uzaiBusinessFeignService.updateExemptionGoodsRedeemedQuantity(exemptionGoodsUpdateRedeemedQuantityDto);
            logger.info("修改官方商品已兑换次数，para={}，result={}", JSONObject.toJSONString(exemptionGoodsUpdateRedeemedQuantityDto), JSONObject.toJSONString(uzaiRespVo));
        }
    }

    @Override
    public Integer countPayOrderWithGoodsId(Long goodsId, Long activityId, Long merId) {

        return mdExchangeMapper.countPayOrderWithGoodsId(goodsId, activityId, merId);

    }

    @Override
    public List<MdExchangeVo> findMdExchangePayList(MdExchangeQuery mdExchangeQuery) {
        //新建返回到页面的LIST对象
        List<MdExchangeVo> mdExchangeVoList = new ArrayList<>();

        //执行分页查询对象
        ArrayList<MdExchange> mdExchangeList = mdExchangeMapper.selectPayExchanges(mdExchangeQuery);
        if (ObjectUtils.isEmpty(mdExchangeList)) {
            return Lists.newArrayList();
        }
        for (MdExchange mdExchange : mdExchangeList) {
            MdExchangeVo mdExchangeVo = new MdExchangeVo();
            BeanUtils.copyProperties(mdExchange, mdExchangeVo);
            mdExchangeVoList.add(mdExchangeVo);
        }
        return mdExchangeVoList;
    }
}
